package fdoj.eventInvitations.servlet;

import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fdoj.eventInvitations.dao.InvantationDao;
import fdoj.eventInvitations.entity.Invantation;
import fdoj.eventInvitations.entity.Person;
import fdoj.eventInvitations.entity.Response;

public class AnswerController extends HttpServlet {
	@EJB
	private InvantationDao invantionDao;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			HttpSession session = request.getSession(true);
			String inv_id = request.getParameter("inv_id");
			Invantation inv = invantionDao.findById(Integer.parseInt(inv_id));
			if (inv != null) {
				if (!inv.getSecurityToken().equals(request.getParameter("st"))) {
					response.sendRedirect(response.encodeRedirectURL("./index"));
					return;
				}
				if(inv.getEvent().getCanceled()){//otkazan
					request.setAttribute("message", "Dogadjaj je otkazan");
					request.setAttribute("redirectURL", "");
					request.setAttribute("title", "Obavestenje");
					request.getRequestDispatcher("/redirectPage.jsp").forward(request, response);
					return;
				}
				if(inv.getEvent().getCheckTime() != null){
					if(inv.getEvent().getCheckTime().before(new Date())){//nije aktivan
						request.setAttribute("message", "Zakasnili ste da se prijavite za dogadjaj." +
								"Poslednji termin za prijavu je " + inv.getEvent().getCheckTime());
						request.setAttribute("redirectURL", "");
						request.setAttribute("title", "Obavestenje");
						request.getRequestDispatcher("/redirectPage.jsp").forward(request, response);
						return;
					}
				}
				if (inv.getStatus().equals(Response.CONFIRMED)
						|| inv.getStatus().equals(Response.DECLINED)) {
					request.setAttribute("alreadyAnswered", true);
					request.getRequestDispatcher("/answer.jsp").forward(
							request, response);
					return;
				}
				inv.setStatus(Response.VISITED_PAGE);
				invantionDao.merge(inv);
				session.setAttribute("answer_inv", inv);
				session.setAttribute("answer_event", inv.getEvent());
				session.setAttribute("answer_contact", inv.getEventCall());
				request.getRequestDispatcher("/answer.jsp").forward(request, response);
				return;
			}else{
				response.sendRedirect(response
						.encodeRedirectURL("./index"));
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
		response.sendRedirect(response.encodeRedirectURL("./error.jsp"));
	}
}
